
/*
 * Copyright (c) 2020 Nanjing Xiaoxiongpai Intelligent Technology Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include "ohos_init.h"
#include "cmsis_os2.h"

#include "wifi_connect.h"

#include "E53_IA1.h"

#include "MQTTClient.h"
#include "wifi_sta_connect.h"

#include "cJSON.h"

static unsigned char sendBuf[1000];
static unsigned char readBuf[1000];

#define WIFI_SSID "KP_IOT_S"
#define WIFI_PWD "12345678"

// #define HOST_ADDR "a1618b7ff0.iot-mqtts.cn-north-4.myhuaweicloud.com"
#define HOST_ADDR "a162664d3a.iot-mqtts.cn-north-4.myhuaweicloud.com"

#define DEVICE_ID "IOT-TEST-002_xdw001"

#define PUBLISH_TOPIC "$oc/devices/"DEVICE_ID"/sys/properties/report"
#define SUBCRIB_TOPIC "$oc/devices/"DEVICE_ID"/sys/commands/#" ///request_id={request_id}"
#define RESPONSE_TOPIC "$oc/devices/"DEVICE_ID"/sys/commands/response" ///request_id={request_id}"


Network network;
MQTTClient client;

void messageArrived(MessageData* data)
{
    int rc;
    printf("Message arrived on topic %.*s: %.*s\n", data->topicName->lenstring.len, data->topicName->lenstring.data,
           data->message->payloadlen, data->message->payload);

    /*
        /xx//x/x//x/requets_id=123456
    */

   //get request id
    char *request_id_idx=NULL;
    char request_id[40]={0};
    request_id_idx = strstr(data->topicName->lenstring.data,"request_id=");
    strncpy(request_id,request_id_idx+11,36);
    printf("request_id = %s\n",request_id);

    //create response topic
    char rsptopic[128]={0};
    sprintf(rsptopic,"%s/request_id=%s",RESPONSE_TOPIC,request_id);
    printf("rsptopic = %s\n",rsptopic);
    printf("msg=%s\n",data->message->payload);
#if 1
    //response message
    MQTTMessage message;
    char payload[300];
    message.qos = 0;
    message.retained = 0;
    message.payload = payload;
    sprintf(payload, "{ \
    \"result_code\": 0, \
    \"response_name\": \"COMMAND_RESPONSE\", \
    \"paras\": { \
        \"result\": \"success\" \
    } \
    }" );
    message.payloadlen = strlen(payload);

    //publish the msg to responese topic
    if ((rc = MQTTPublish(&client, rsptopic, &message)) != 0) {
        printf("Return code from MQTT publish is %d\n", rc);
        NetworkDisconnect(&network);
        MQTTDisconnect(&client);
        
    }
    #endif
    cJSON *root = cJSON_ParseWithLength( data->message->payload, data->message->payloadlen);
    if(root != NULL){
        cJSON *cmd_name = cJSON_GetObjectItem(root,"command_name");
        if(cmd_name != NULL){
            char *cmd_name_str = cJSON_GetStringValue(cmd_name);

            if(strcmp(cmd_name_str,"Agriculture_Control_Light") == 0){
                 cJSON *para_obj = cJSON_GetObjectItem(root,"paras");
                 if(para_obj){
                      cJSON *lightParam = cJSON_GetObjectItem(para_obj,"LightStatus");
                      if(strcmp(cJSON_GetStringValue(lightParam),"ON") == 0){
                        LightStatusSet(ON);
                      }else{
                         LightStatusSet(OFF);
                      }
                 }
            }else if(strcmp(cmd_name_str,"Agriculture_Control_Motor") == 0){
                 cJSON *para_obj = cJSON_GetObjectItem(root,"paras");
                 if(para_obj){
                      cJSON *motorParam = cJSON_GetObjectItem(para_obj,"MotorStatus");
                      if(strcmp(cJSON_GetStringValue(motorParam),"ON") == 0){
                         MotorStatusSet(ON);
                      }else{
                         MotorStatusSet(OFF);
                      }
                 }
            }

        }

        cJSON_Delete(root);

    }

}




static void get_sensor_public_string(char *payload){
	
        MQTTMessage message;
        // char *publishtopic="$oc/devices/test_fan_1/sys/properties/report";

        E53IA1Data data;
   
        E53IA1ReadData(&data);
        cJSON *root = cJSON_CreateObject();
        
        if(root != NULL){

            cJSON *serv_arr = cJSON_AddArrayToObject(root, "services");

            cJSON *arr_item =  cJSON_CreateObject();

            cJSON_AddStringToObject(arr_item,"service_id","Agriculture");

            cJSON *pro_obj = cJSON_CreateObject();
            cJSON_AddItemToObject(arr_item,"properties",pro_obj);
            cJSON_AddNumberToObject(pro_obj,"Temperature",data.Temperature);
            cJSON_AddNumberToObject(pro_obj,"Humidity",data.Humidity);
         

            cJSON_AddItemToArray(serv_arr,arr_item);

            char *palyload_str = cJSON_PrintUnformatted(root);

            strcpy(payload,palyload_str);

            cJSON_free(palyload_str);
            cJSON_Delete(root);

        }
}

static void MQTTDemoTask(void)
{
    E53IA1Init();
    printf(">> MQTTDemoTask ...\n");
    WifiConnect(WIFI_SSID, WIFI_PWD);
    printf("Starting ...\n");
    int rc, count = 0;
    // MQTTClient client;


    NetworkInit(&network);
    printf("NetworkConnect  ...\n");


begin:
    NetworkConnect(&network, HOST_ADDR, 1883);
    printf("MQTTClientInit  ...\n");
    MQTTClientInit(&client, &network, 2000, sendBuf, sizeof(sendBuf), readBuf, sizeof(readBuf));

    MQTTString clientId = MQTTString_initializer;
    clientId.cstring = "IOT-TEST-002_xdw001_0_0_2022111914"; //"1234abcdef_0_0_2022101103";

    MQTTString userName = MQTTString_initializer;
    userName.cstring = DEVICE_ID; //"1234abcdef"; //deviceID

    MQTTString password = MQTTString_initializer;
    password.cstring = "1f27b83dbe31da888a43f8936a79e83e15f156725b9224014feed86d51d558f9"; //"be64416f73bad92de15bd2d266c71dbce661fb985adfa5feb7e7f68e51bda8bf";

    MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
    data.clientID = clientId;

    data.username = userName;
	data.password = password;

    data.willFlag = 0;
    data.MQTTVersion = 4;
    data.keepAliveInterval = 60;
    data.cleansession = 1;

    printf("MQTTConnect  ...\n");
    rc = MQTTConnect(&client, &data);
    if (rc != 0) {
        printf("MQTTConnect: %d\n", rc);
        NetworkDisconnect(&network);
        MQTTDisconnect(&client);
        osDelay(200);
        goto begin;
    }

    printf("MQTTSubscribe  ...\n");
    rc = MQTTSubscribe(&client, SUBCRIB_TOPIC, 0, messageArrived);

    if (rc != 0) {
        printf("MQTTSubscribe: %d\n", rc);
        osDelay(200);
        goto begin;
    }

    while (1) {
        MQTTMessage message;
		char payload[500]={0};
        get_sensor_public_string(payload);
     
        message.qos = 0;
        message.retained = 0;
        message.payload = payload;
     
        message.payloadlen = strlen(payload);

        if ((rc = MQTTPublish(&client, PUBLISH_TOPIC, &message)) != 0) {
            printf("Return code from MQTT publish is %d\n", rc);
            NetworkDisconnect(&network);
            MQTTDisconnect(&client);
            goto begin;
        }else{
            printf("mqtt publish success:%s\n",payload);
        }
        MQTTYield(&client, 5000);
        //sleep(3);
        // osDelay(500);
    }
}  


static void OC_Demo(void)
{
    osThreadAttr_t attr;

    attr.name = "MQTTDemoTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 10240;
    attr.priority = 24;

    if (osThreadNew((osThreadFunc_t)MQTTDemoTask, NULL, &attr) == NULL)
    {
        printf("Falied to create MQTTDemoTask!\n");
    }

}




APP_FEATURE_INIT(OC_Demo);
//SYS_RUN(OC_Demo);
